
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content>
  

  
    <meta name="description" content="Go语言之结构体">
  
  
  
  <link rel="icon" type="image/x-icon" href="/images/footer-logo.png">
  
  <title>Go语言之结构体 [ 51AIOps 专注于运维自动化  微信： kaipython ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    
    <span class="title" style="text-transform:none">51AIOps 专注于运维自动化  微信： kaipython</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            
              <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
            
          
      
  </ul>
   
</nav>

  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner" style='margin-left:-68px!important'>
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        Go语言之结构体
      </h1>
      <span>
        
        <time class="time" datetime="2020-08-28T16:00:00.000Z">
        2020-08-29
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <p>Go语言中没有“类”的概念，也不支持“类”的继承等面向对象的概念。Go语言中通过结构体的内嵌再配合接口比面向对象具有更高的扩展性和灵活性。</p>
<h1 id="类型别名和自定义类型"><a href="#类型别名和自定义类型" class="headerlink" title="类型别名和自定义类型"></a>类型别名和自定义类型</h1><h2 id="自定义类型"><a href="#自定义类型" class="headerlink" title="自定义类型"></a>自定义类型</h2><p>在Go语言中有一些基本的数据类型，如<code>string</code>、<code>整型</code>、<code>浮点型</code>、<code>布尔</code>等数据类型， Go语言中可以使用<code>type</code>关键字来定义自定义类型。</p>
<p>自定义类型是定义了一个全新的类型。我们可以基于内置的基本类型定义，也可以通过struct定义。例如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//将MyInt定义为int类型</span></span><br><span class="line"><span class="keyword">type</span> MyInt <span class="keyword">int</span></span><br></pre></td></tr></table></figure>

<p>通过<code>type</code>关键字的定义，<code>MyInt</code>就是一种新的类型，它具有<code>int</code>的特性。</p>
<h2 id="类型别名"><a href="#类型别名" class="headerlink" title="类型别名"></a>类型别名</h2><p>类型别名是<code>Go1.9</code>版本添加的新功能。</p>
<p>类型别名规定：TypeAlias只是Type的别名，本质上TypeAlias与Type是同一个类型。就像一个孩子小时候有小名、乳名，上学后用学名，英语老师又会给他起英文名，但这些名字都指的是他本人。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> TypeAlias = Type</span><br></pre></td></tr></table></figure>

<p>我们之前见过的<code>rune</code>和<code>byte</code>就是类型别名，他们的定义如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="keyword">byte</span> = <span class="keyword">uint8</span></span><br><span class="line"><span class="keyword">type</span> <span class="keyword">rune</span> = <span class="keyword">int32</span></span><br></pre></td></tr></table></figure>

<h2 id="类型定义和类型别名的区别"><a href="#类型定义和类型别名的区别" class="headerlink" title="类型定义和类型别名的区别"></a>类型定义和类型别名的区别</h2><p>类型别名与类型定义表面上看只有一个等号的差异，我们通过下面的这段代码来理解它们之间的区别。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//类型定义</span></span><br><span class="line"><span class="keyword">type</span> NewInt <span class="keyword">int</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//类型别名</span></span><br><span class="line"><span class="keyword">type</span> MyInt = <span class="keyword">int</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> a NewInt</span><br><span class="line">	<span class="keyword">var</span> b MyInt</span><br><span class="line">	</span><br><span class="line">	fmt.Printf(<span class="string">"type of a:%T\n"</span>, a) <span class="comment">//type of a:main.NewInt</span></span><br><span class="line">	fmt.Printf(<span class="string">"type of b:%T\n"</span>, b) <span class="comment">//type of b:int</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果显示a的类型是<code>main.NewInt</code>，表示main包下定义的<code>NewInt</code>类型。b的类型是<code>int</code>。<code>MyInt</code>类型只会在代码中存在，编译完成时并不会有<code>MyInt</code>类型。</p>
<h1 id="结构体"><a href="#结构体" class="headerlink" title="结构体"></a>结构体</h1><p>Go语言中的基础数据类型可以表示一些事物的基本属性，但是当我们想表达一个事物的全部或部分属性时，这时候再用单一的基本数据类型明显就无法满足需求了，Go语言提供了一种自定义数据类型，可以封装多个基本数据类型，这种数据类型叫结构体，英文名称<code>struct</code>。 也就是我们可以通过<code>struct</code>来定义自己的类型了。</p>
<p>Go语言中通过<code>struct</code>来实现面向对象。</p>
<h2 id="结构体的定义"><a href="#结构体的定义" class="headerlink" title="结构体的定义"></a>结构体的定义</h2><p>使用<code>type</code>和<code>struct</code>关键字来定义结构体，具体代码格式如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> 类型名 <span class="keyword">struct</span> &#123;</span><br><span class="line">    字段名 字段类型</span><br><span class="line">    字段名 字段类型</span><br><span class="line">    …</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中：</p>
<ul>
<li>类型名：标识自定义结构体的名称，在同一个包内不能重复。</li>
<li>字段名：表示结构体字段名。结构体中的字段名必须唯一。</li>
<li>字段类型：表示结构体字段的具体类型。</li>
</ul>
<p>举个例子，我们定义一个<code>Person</code>（人）结构体，代码如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> person <span class="keyword">struct</span> &#123;</span><br><span class="line">	name <span class="keyword">string</span></span><br><span class="line">	city <span class="keyword">string</span></span><br><span class="line">	age  <span class="keyword">int8</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>同样类型的字段也可以写在一行，</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> person1 <span class="keyword">struct</span> &#123;</span><br><span class="line">	name, city <span class="keyword">string</span></span><br><span class="line">	age        <span class="keyword">int8</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样我们就拥有了一个<code>person</code>的自定义类型，它有<code>name</code>、<code>city</code>、<code>age</code>三个字段，分别表示姓名、城市和年龄。这样我们使用这个<code>person</code>结构体就能够很方便的在程序中表示和存储人信息了。</p>
<p>语言内置的基础数据类型是用来描述一个值的，而结构体是用来描述一组值的。比如一个人有名字、年龄和居住城市等，本质上是一种聚合型的数据类型</p>
<h2 id="结构体实例化"><a href="#结构体实例化" class="headerlink" title="结构体实例化"></a>结构体实例化</h2><p>只有当结构体实例化时，才会真正地分配内存。也就是必须实例化后才能使用结构体的字段。</p>
<p>结构体本身也是一种类型，我们可以像声明内置类型一样使用<code>var</code>关键字声明结构体类型。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> 结构体实例 结构体类型</span><br></pre></td></tr></table></figure>

<h3 id="基本实例化"><a href="#基本实例化" class="headerlink" title="基本实例化"></a>基本实例化</h3><p>举个例子：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> person <span class="keyword">struct</span> &#123;</span><br><span class="line">	name <span class="keyword">string</span></span><br><span class="line">	city <span class="keyword">string</span></span><br><span class="line">	age  <span class="keyword">int8</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> p1 person</span><br><span class="line">	p1.name = <span class="string">"szk"</span></span><br><span class="line">	p1.city = <span class="string">"北京"</span></span><br><span class="line">	p1.age = <span class="number">18</span></span><br><span class="line">	fmt.Printf(<span class="string">"p1=%v\n"</span>, p1)  <span class="comment">//p1=&#123;szk 北京 18&#125;</span></span><br><span class="line">	fmt.Printf(<span class="string">"p1=%#v\n"</span>, p1) <span class="comment">//p1=main.person&#123;name:"szk", city:"北京", age:18&#125;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们通过<code>.</code>来访问结构体的字段（成员变量）,例如<code>p1.name</code>和<code>p1.age</code>等。</p>
<h3 id="匿名结构体"><a href="#匿名结构体" class="headerlink" title="匿名结构体"></a>匿名结构体</h3><p>在定义一些临时数据结构等场景下还可以使用匿名结构体。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line">     </span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line">     </span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">var</span> user <span class="keyword">struct</span>&#123;Name <span class="keyword">string</span>; Age <span class="keyword">int</span>&#125;</span><br><span class="line">    user.Name = <span class="string">"小王子"</span></span><br><span class="line">    user.Age = <span class="number">18</span></span><br><span class="line">    fmt.Printf(<span class="string">"%#v\n"</span>, user)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="创建指针类型结构体"><a href="#创建指针类型结构体" class="headerlink" title="创建指针类型结构体"></a>创建指针类型结构体</h3><p>我们还可以通过使用<code>new</code>关键字对结构体进行实例化，得到的是结构体的地址。 格式如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p2 = <span class="built_in">new</span>(person)</span><br><span class="line">fmt.Printf(<span class="string">"%T\n"</span>, p2)     <span class="comment">//*main.person</span></span><br><span class="line">fmt.Printf(<span class="string">"p2=%#v\n"</span>, p2) <span class="comment">//p2=&amp;main.person&#123;name:"", city:"", age:0&#125;</span></span><br></pre></td></tr></table></figure>

<p>从打印的结果中我们可以看出<code>p2</code>是一个结构体指针。</p>
<p>需要注意的是在Go语言中支持对结构体指针直接使用<code>.</code>来访问结构体的成员。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p2 = <span class="built_in">new</span>(person)</span><br><span class="line">p2.name = <span class="string">"小王子"</span></span><br><span class="line">p2.age = <span class="number">28</span></span><br><span class="line">p2.city = <span class="string">"上海"</span></span><br><span class="line">fmt.Printf(<span class="string">"p2=%#v\n"</span>, p2) <span class="comment">//p2=&amp;main.person&#123;name:"小王子", city:"上海", age:28&#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="取结构体的地址实例化"><a href="#取结构体的地址实例化" class="headerlink" title="取结构体的地址实例化"></a>取结构体的地址实例化</h3><p>使用<code>&amp;</code>对结构体进行取地址操作相当于对该结构体类型进行了一次<code>new</code>实例化操作。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">p3 := &amp;person&#123;&#125;</span><br><span class="line">fmt.Printf(<span class="string">"%T\n"</span>, p3)     <span class="comment">//*main.person</span></span><br><span class="line">fmt.Printf(<span class="string">"p3=%#v\n"</span>, p3) <span class="comment">//p3=&amp;main.person&#123;name:"", city:"", age:0&#125;</span></span><br><span class="line">p3.name = <span class="string">"szk"</span></span><br><span class="line">p3.age = <span class="number">30</span></span><br><span class="line">p3.city = <span class="string">"成都"</span></span><br><span class="line">fmt.Printf(<span class="string">"p3=%#v\n"</span>, p3) <span class="comment">//p3=&amp;main.person&#123;name:"szk", city:"成都", age:30&#125;</span></span><br></pre></td></tr></table></figure>

<p><code>p3.name = &quot;szk&quot;</code>其实在底层是<code>(*p3).name = &quot;szk&quot;</code>，这是Go语言帮我们实现的语法糖。</p>
<h2 id="结构体初始化"><a href="#结构体初始化" class="headerlink" title="结构体初始化"></a>结构体初始化</h2><p>没有初始化的结构体，其成员变量都是对应其类型的零值。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> person <span class="keyword">struct</span> &#123;</span><br><span class="line">	name <span class="keyword">string</span></span><br><span class="line">	city <span class="keyword">string</span></span><br><span class="line">	age  <span class="keyword">int8</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> p4 person</span><br><span class="line">	fmt.Printf(<span class="string">"p4=%#v\n"</span>, p4) <span class="comment">//p4=main.person&#123;name:"", city:"", age:0&#125;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="使用键值对初始化"><a href="#使用键值对初始化" class="headerlink" title="使用键值对初始化"></a>使用键值对初始化</h3><p>使用键值对对结构体进行初始化时，键对应结构体的字段，值对应该字段的初始值。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">p5 := person&#123;</span><br><span class="line">	name: <span class="string">"小王子"</span>,</span><br><span class="line">	city: <span class="string">"北京"</span>,</span><br><span class="line">	age:  <span class="number">18</span>,</span><br><span class="line">&#125;</span><br><span class="line">fmt.Printf(<span class="string">"p5=%#v\n"</span>, p5) <span class="comment">//p5=main.person&#123;name:"小王子", city:"北京", age:18&#125;</span></span><br></pre></td></tr></table></figure>

<p>也可以对结构体指针进行键值对初始化，例如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">p6 := &amp;person&#123;</span><br><span class="line">	name: <span class="string">"小王子"</span>,</span><br><span class="line">	city: <span class="string">"北京"</span>,</span><br><span class="line">	age:  <span class="number">18</span>,</span><br><span class="line">&#125;</span><br><span class="line">fmt.Printf(<span class="string">"p6=%#v\n"</span>, p6) <span class="comment">//p6=&amp;main.person&#123;name:"小王子", city:"北京", age:18&#125;</span></span><br></pre></td></tr></table></figure>

<p>当某些字段没有初始值的时候，该字段可以不写。此时，没有指定初始值的字段的值就是该字段类型的零值。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">p7 := &amp;person&#123;</span><br><span class="line">	city: <span class="string">"北京"</span>,</span><br><span class="line">&#125;</span><br><span class="line">fmt.Printf(<span class="string">"p7=%#v\n"</span>, p7) <span class="comment">//p7=&amp;main.person&#123;name:"", city:"北京", age:0&#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="使用值的列表初始化"><a href="#使用值的列表初始化" class="headerlink" title="使用值的列表初始化"></a>使用值的列表初始化</h3><p>初始化结构体的时候可以简写，也就是初始化的时候不写键，直接写值：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">p8 := &amp;person&#123;</span><br><span class="line">	<span class="string">"沙河娜扎"</span>,</span><br><span class="line">	<span class="string">"北京"</span>,</span><br><span class="line">	<span class="number">28</span>,</span><br><span class="line">&#125;</span><br><span class="line">fmt.Printf(<span class="string">"p8=%#v\n"</span>, p8) <span class="comment">//p8=&amp;main.person&#123;name:"沙河娜扎", city:"北京", age:28&#125;</span></span><br></pre></td></tr></table></figure>

<p>使用这种格式初始化时，需要注意：</p>
<ol>
<li>必须初始化结构体的所有字段。</li>
<li>初始值的填充顺序必须与字段在结构体中的声明顺序一致。</li>
<li>该方式不能和键值初始化方式混用。</li>
</ol>
<h2 id="结构体内存布局"><a href="#结构体内存布局" class="headerlink" title="结构体内存布局"></a>结构体内存布局</h2><p>结构体占用一块连续的内存。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> test <span class="keyword">struct</span> &#123;</span><br><span class="line">	a <span class="keyword">int8</span></span><br><span class="line">	b <span class="keyword">int8</span></span><br><span class="line">	c <span class="keyword">int8</span></span><br><span class="line">	d <span class="keyword">int8</span></span><br><span class="line">&#125;</span><br><span class="line">n := test&#123;</span><br><span class="line">	<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>,</span><br><span class="line">&#125;</span><br><span class="line">fmt.Printf(<span class="string">"n.a %p\n"</span>, &amp;n.a)</span><br><span class="line">fmt.Printf(<span class="string">"n.b %p\n"</span>, &amp;n.b)</span><br><span class="line">fmt.Printf(<span class="string">"n.c %p\n"</span>, &amp;n.c)</span><br><span class="line">fmt.Printf(<span class="string">"n.d %p\n"</span>, &amp;n.d)</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">n.a 0xc0000a0060</span><br><span class="line">n.b 0xc0000a0061</span><br><span class="line">n.c 0xc0000a0062</span><br><span class="line">n.d 0xc0000a0063</span><br></pre></td></tr></table></figure>

<h3 id="空结构体"><a href="#空结构体" class="headerlink" title="空结构体"></a>空结构体</h3><p>空结构体是不占用空间的。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> v <span class="keyword">struct</span>&#123;&#125;</span><br><span class="line">fmt.Println(unsafe.Sizeof(v))  <span class="comment">// 0</span></span><br></pre></td></tr></table></figure>

<h2 id="面试题"><a href="#面试题" class="headerlink" title="面试题"></a>面试题</h2><p>请问下面代码的执行结果是什么？</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> student <span class="keyword">struct</span> &#123;</span><br><span class="line">	name <span class="keyword">string</span></span><br><span class="line">	age  <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	m := <span class="built_in">make</span>(<span class="keyword">map</span>[<span class="keyword">string</span>]*student)</span><br><span class="line">	stus := []student&#123;</span><br><span class="line">		&#123;name: <span class="string">"小王子"</span>, age: <span class="number">18</span>&#125;,</span><br><span class="line">		&#123;name: <span class="string">"szk"</span>, age: <span class="number">23</span>&#125;,</span><br><span class="line">		&#123;name: <span class="string">"大王八"</span>, age: <span class="number">9000</span>&#125;,</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">for</span> _, stu := <span class="keyword">range</span> stus &#123;</span><br><span class="line">		m[stu.name] = &amp;stu</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> k, v := <span class="keyword">range</span> m &#123;</span><br><span class="line">		fmt.Println(k, <span class="string">"=&gt;"</span>, v.name)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="构造函数"><a href="#构造函数" class="headerlink" title="构造函数"></a>构造函数</h2><p>Go语言的结构体没有构造函数，我们可以自己实现。 例如，下方的代码就实现了一个<code>person</code>的构造函数。 因为<code>struct</code>是值类型，如果结构体比较复杂的话，值拷贝性能开销会比较大，所以该构造函数返回的是结构体指针类型。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">newPerson</span><span class="params">(name, city <span class="keyword">string</span>, age <span class="keyword">int8</span>)</span> *<span class="title">person</span></span> &#123;</span><br><span class="line">	<span class="keyword">return</span> &amp;person&#123;</span><br><span class="line">		name: name,</span><br><span class="line">		city: city,</span><br><span class="line">		age:  age,</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>调用构造函数</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">p9 := newPerson(<span class="string">"张三"</span>, <span class="string">"沙河"</span>, <span class="number">90</span>)</span><br><span class="line">fmt.Printf(<span class="string">"%#v\n"</span>, p9) <span class="comment">//&amp;main.person&#123;name:"张三", city:"沙河", age:90&#125;</span></span><br></pre></td></tr></table></figure>

<h2 id="方法和接收者"><a href="#方法和接收者" class="headerlink" title="方法和接收者"></a>方法和接收者</h2><p>Go语言中的<code>方法（Method）</code>是一种作用于特定类型变量的函数。这种特定类型变量叫做<code>接收者（Receiver）</code>。接收者的概念就类似于其他语言中的<code>this</code>或者 <code>self</code>。</p>
<p>方法的定义格式如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(接收者变量 接收者类型)</span> 方法名<span class="params">(参数列表)</span> <span class="params">(返回参数)</span></span> &#123;</span><br><span class="line">    函数体</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中，</p>
<ul>
<li>接收者变量：接收者中的参数变量名在命名时，官方建议使用接收者类型名称首字母的小写，而不是<code>self</code>、<code>this</code>之类的命名。例如，<code>Person</code>类型的接收者变量应该命名为 <code>p</code>，<code>Connector</code>类型的接收者变量应该命名为<code>c</code>等。</li>
<li>接收者类型：接收者类型和参数类似，可以是指针类型和非指针类型。</li>
<li>方法名、参数列表、返回参数：具体格式与函数定义相同。</li>
</ul>
<p>举个例子：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Person 结构体</span></span><br><span class="line"><span class="keyword">type</span> Person <span class="keyword">struct</span> &#123;</span><br><span class="line">	name <span class="keyword">string</span></span><br><span class="line">	age  <span class="keyword">int8</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//NewPerson 构造函数</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">NewPerson</span><span class="params">(name <span class="keyword">string</span>, age <span class="keyword">int8</span>)</span> *<span class="title">Person</span></span> &#123;</span><br><span class="line">	<span class="keyword">return</span> &amp;Person&#123;</span><br><span class="line">		name: name,</span><br><span class="line">		age:  age,</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//Dream Person做梦的方法</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p Person)</span> <span class="title">Dream</span><span class="params">()</span></span> &#123;</span><br><span class="line">	fmt.Printf(<span class="string">"%s的梦想是学好Go语言！\n"</span>, p.name)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	p1 := NewPerson(<span class="string">"小王子"</span>, <span class="number">25</span>)</span><br><span class="line">	p1.Dream()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>方法与函数的区别是，函数不属于任何类型，方法属于特定的类型。</p>
<h3 id="指针类型的接收者"><a href="#指针类型的接收者" class="headerlink" title="指针类型的接收者"></a>指针类型的接收者</h3><p>指针类型的接收者由一个结构体的指针组成，由于指针的特性，调用方法时修改接收者指针的任意成员变量，在方法结束后，修改都是有效的。这种方式就十分接近于其他语言中面向对象中的<code>this</code>或者<code>self</code>。 例如我们为<code>Person</code>添加一个<code>SetAge</code>方法，来修改实例变量的年龄。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// SetAge 设置p的年龄</span></span><br><span class="line"><span class="comment">// 使用指针接收者</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p *Person)</span> <span class="title">SetAge</span><span class="params">(newAge <span class="keyword">int8</span>)</span></span> &#123;</span><br><span class="line">	p.age = newAge</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>调用该方法：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	p1 := NewPerson(<span class="string">"小王子"</span>, <span class="number">25</span>)</span><br><span class="line">	fmt.Println(p1.age) <span class="comment">// 25</span></span><br><span class="line">	p1.SetAge(<span class="number">30</span>)</span><br><span class="line">	fmt.Println(p1.age) <span class="comment">// 30</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="值类型的接收者"><a href="#值类型的接收者" class="headerlink" title="值类型的接收者"></a>值类型的接收者</h3><p>当方法作用于值类型接收者时，Go语言会在代码运行时将接收者的值复制一份。在值类型接收者的方法中可以获取接收者的成员值，但修改操作只是针对副本，无法修改接收者变量本身。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// SetAge2 设置p的年龄</span></span><br><span class="line"><span class="comment">// 使用值接收者</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p Person)</span> <span class="title">SetAge2</span><span class="params">(newAge <span class="keyword">int8</span>)</span></span> &#123;</span><br><span class="line">	p.age = newAge</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	p1 := NewPerson(<span class="string">"小王子"</span>, <span class="number">25</span>)</span><br><span class="line">	p1.Dream()</span><br><span class="line">	fmt.Println(p1.age) <span class="comment">// 25</span></span><br><span class="line">	p1.SetAge2(<span class="number">30</span>) <span class="comment">// (*p1).SetAge2(30)</span></span><br><span class="line">	fmt.Println(p1.age) <span class="comment">// 25</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="什么时候应该使用指针类型接收者"><a href="#什么时候应该使用指针类型接收者" class="headerlink" title="什么时候应该使用指针类型接收者"></a>什么时候应该使用指针类型接收者</h3><ol>
<li>需要修改接收者中的值</li>
<li>接收者是拷贝代价比较大的大对象</li>
<li>保证一致性，如果有某个方法使用了指针接收者，那么其他的方法也应该使用指针接收者。</li>
</ol>
<h2 id="任意类型添加方法"><a href="#任意类型添加方法" class="headerlink" title="任意类型添加方法"></a>任意类型添加方法</h2><p>在Go语言中，接收者的类型可以是任何类型，不仅仅是结构体，任何类型都可以拥有方法。 举个例子，我们基于内置的<code>int</code>类型使用type关键字可以定义新的自定义类型，然后为我们的自定义类型添加方法。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//MyInt 将int定义为自定义MyInt类型</span></span><br><span class="line"><span class="keyword">type</span> MyInt <span class="keyword">int</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//SayHello 为MyInt添加一个SayHello的方法</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(m MyInt)</span> <span class="title">SayHello</span><span class="params">()</span></span> &#123;</span><br><span class="line">	fmt.Println(<span class="string">"Hello, 我是一个int。"</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> m1 MyInt</span><br><span class="line">	m1.SayHello() <span class="comment">//Hello, 我是一个int。</span></span><br><span class="line">	m1 = <span class="number">100</span></span><br><span class="line">	fmt.Printf(<span class="string">"%#v  %T\n"</span>, m1, m1) <span class="comment">//100  main.MyInt</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>注意事项：</strong> 非本地类型不能定义方法，也就是说我们不能给别的包的类型定义方法。</p>
<h2 id="结构体字段的可见性"><a href="#结构体字段的可见性" class="headerlink" title="结构体字段的可见性"></a>结构体字段的可见性</h2><p>结构体中字段大写开头表示可公开访问，小写表示私有（仅在定义当前结构体的包中可访问）。</p>
<h2 id="结构体与JSON序列化"><a href="#结构体与JSON序列化" class="headerlink" title="结构体与JSON序列化"></a>结构体与JSON序列化</h2><p>JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。JSON键值对是用来保存JS对象的一种方式，键/值对组合中的键名写在前面并用双引号<code>&quot;&quot;</code>包裹，使用冒号<code>:</code>分隔，然后紧接着值；多个键值之间使用英文<code>,</code>分隔。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Student 学生</span></span><br><span class="line"><span class="keyword">type</span> Student <span class="keyword">struct</span> &#123;</span><br><span class="line">	ID     <span class="keyword">int</span></span><br><span class="line">	Gender <span class="keyword">string</span></span><br><span class="line">	Name   <span class="keyword">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//Class 班级</span></span><br><span class="line"><span class="keyword">type</span> Class <span class="keyword">struct</span> &#123;</span><br><span class="line">	Title    <span class="keyword">string</span></span><br><span class="line">	Students []*Student</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	c := &amp;Class&#123;</span><br><span class="line">		Title:    <span class="string">"101"</span>,</span><br><span class="line">		Students: <span class="built_in">make</span>([]*Student, <span class="number">0</span>, <span class="number">200</span>),</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">for</span> i := <span class="number">0</span>; i &lt; <span class="number">10</span>; i++ &#123;</span><br><span class="line">		stu := &amp;Student&#123;</span><br><span class="line">			Name:   fmt.Sprintf(<span class="string">"stu%02d"</span>, i),</span><br><span class="line">			Gender: <span class="string">"男"</span>,</span><br><span class="line">			ID:     i,</span><br><span class="line">		&#125;</span><br><span class="line">		c.Students = <span class="built_in">append</span>(c.Students, stu)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//JSON序列化：结构体--&gt;JSON格式的字符串</span></span><br><span class="line">	data, err := json.Marshal(c)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Println(<span class="string">"json marshal failed"</span>)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Printf(<span class="string">"json:%s\n"</span>, data)</span><br><span class="line">	<span class="comment">//JSON反序列化：JSON格式的字符串--&gt;结构体</span></span><br><span class="line">	str := <span class="string">`&#123;"Title":"101","Students":[&#123;"ID":0,"Gender":"男","Name":"stu00"&#125;,&#123;"ID":1,"Gender":"男","Name":"stu01"&#125;,&#123;"ID":2,"Gender":"男","Name":"stu02"&#125;,&#123;"ID":3,"Gender":"男","Name":"stu03"&#125;,&#123;"ID":4,"Gender":"男","Name":"stu04"&#125;,&#123;"ID":5,"Gender":"男","Name":"stu05"&#125;,&#123;"ID":6,"Gender":"男","Name":"stu06"&#125;,&#123;"ID":7,"Gender":"男","Name":"stu07"&#125;,&#123;"ID":8,"Gender":"男","Name":"stu08"&#125;,&#123;"ID":9,"Gender":"男","Name":"stu09"&#125;]&#125;`</span></span><br><span class="line">	c1 := &amp;Class&#123;&#125;</span><br><span class="line">	err = json.Unmarshal([]<span class="keyword">byte</span>(str), c1)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Println(<span class="string">"json unmarshal failed!"</span>)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Printf(<span class="string">"%#v\n"</span>, c1)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="结构体标签（Tag）"><a href="#结构体标签（Tag）" class="headerlink" title="结构体标签（Tag）"></a>结构体标签（Tag）</h2><p><code>Tag</code>是结构体的元信息，可以在运行的时候通过反射的机制读取出来。 <code>Tag</code>在结构体字段的后方定义，由一对<strong>反引号</strong>包裹起来，具体的格式如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">`key1:<span class="string">"value1"</span> key2:<span class="string">"value2"</span>`</span><br></pre></td></tr></table></figure>

<p>结构体tag由一个或多个键值对组成。键与值使用冒号分隔，值用双引号括起来。同一个结构体字段可以设置多个键值对tag，不同的键值对之间使用空格分隔。</p>
<p><strong>注意事项：</strong> 为结构体编写<code>Tag</code>时，必须严格遵守键值对的规则。结构体标签的解析代码的容错能力很差，一旦格式写错，编译和运行时都不会提示任何错误，通过反射也无法正确取值。例如不要在key和value之间添加空格。</p>
<p>例如我们为<code>Student</code>结构体的每个字段定义json序列化时使用的Tag：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Student 学生</span></span><br><span class="line"><span class="keyword">type</span> Student <span class="keyword">struct</span> &#123;</span><br><span class="line">	ID     <span class="keyword">int</span>    <span class="string">`json:"id"`</span> <span class="comment">//通过指定tag实现json序列化该字段时的key</span></span><br><span class="line">	Gender <span class="keyword">string</span> <span class="comment">//json序列化是默认使用字段名作为key</span></span><br><span class="line">	name   <span class="keyword">string</span> <span class="comment">//私有不能被json包访问</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	s1 := Student&#123;</span><br><span class="line">		ID:     <span class="number">1</span>,</span><br><span class="line">		Gender: <span class="string">"男"</span>,</span><br><span class="line">		name:   <span class="string">"szk"</span>,</span><br><span class="line">	&#125;</span><br><span class="line">	data, err := json.Marshal(s1)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Println(<span class="string">"json marshal failed!"</span>)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Printf(<span class="string">"json str:%s\n"</span>, data) <span class="comment">//json str:&#123;"id":1,"Gender":"男"&#125;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="结构体和方法补充知识点"><a href="#结构体和方法补充知识点" class="headerlink" title="结构体和方法补充知识点"></a>结构体和方法补充知识点</h2><p>因为slice和map这两种数据类型都包含了指向底层数据的指针，因此我们在需要复制它们时要特别注意。我们来看下面的例子：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Person <span class="keyword">struct</span> &#123;</span><br><span class="line">	name   <span class="keyword">string</span></span><br><span class="line">	age    <span class="keyword">int8</span></span><br><span class="line">	dreams []<span class="keyword">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p *Person)</span> <span class="title">SetDreams</span><span class="params">(dreams []<span class="keyword">string</span>)</span></span> &#123;</span><br><span class="line">	p.dreams = dreams</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	p1 := Person&#123;name: <span class="string">"小王子"</span>, age: <span class="number">18</span>&#125;</span><br><span class="line">	data := []<span class="keyword">string</span>&#123;<span class="string">"吃饭"</span>, <span class="string">"睡觉"</span>, <span class="string">"打豆豆"</span>&#125;</span><br><span class="line">	p1.SetDreams(data)</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 你真的想要修改 p1.dreams 吗？</span></span><br><span class="line">	data[<span class="number">1</span>] = <span class="string">"不睡觉"</span></span><br><span class="line">	fmt.Println(p1.dreams)  <span class="comment">// ?</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>正确的做法是在方法中使用传入的slice的拷贝进行结构体赋值。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(p *Person)</span> <span class="title">SetDreams</span><span class="params">(dreams []<span class="keyword">string</span>)</span></span> &#123;</span><br><span class="line">	p.dreams = <span class="built_in">make</span>([]<span class="keyword">string</span>, <span class="built_in">len</span>(dreams))</span><br><span class="line">	<span class="built_in">copy</span>(p.dreams, dreams)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>同样的问题也存在于返回值slice和map的情况，在实际编码过程中一定要注意这个问题。</p>

    </div>

  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#类型别名和自定义类型"><span class="toc-text">类型别名和自定义类型</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#自定义类型"><span class="toc-text">自定义类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#类型别名"><span class="toc-text">类型别名</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#类型定义和类型别名的区别"><span class="toc-text">类型定义和类型别名的区别</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#结构体"><span class="toc-text">结构体</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#结构体的定义"><span class="toc-text">结构体的定义</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#结构体实例化"><span class="toc-text">结构体实例化</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#基本实例化"><span class="toc-text">基本实例化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#匿名结构体"><span class="toc-text">匿名结构体</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#创建指针类型结构体"><span class="toc-text">创建指针类型结构体</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#取结构体的地址实例化"><span class="toc-text">取结构体的地址实例化</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#结构体初始化"><span class="toc-text">结构体初始化</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#使用键值对初始化"><span class="toc-text">使用键值对初始化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用值的列表初始化"><span class="toc-text">使用值的列表初始化</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#结构体内存布局"><span class="toc-text">结构体内存布局</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#空结构体"><span class="toc-text">空结构体</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#面试题"><span class="toc-text">面试题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#构造函数"><span class="toc-text">构造函数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#方法和接收者"><span class="toc-text">方法和接收者</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#指针类型的接收者"><span class="toc-text">指针类型的接收者</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#值类型的接收者"><span class="toc-text">值类型的接收者</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#什么时候应该使用指针类型接收者"><span class="toc-text">什么时候应该使用指针类型接收者</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#任意类型添加方法"><span class="toc-text">任意类型添加方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#结构体字段的可见性"><span class="toc-text">结构体字段的可见性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#结构体与JSON序列化"><span class="toc-text">结构体与JSON序列化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#结构体标签（Tag）"><span class="toc-text">结构体标签（Tag）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#结构体和方法补充知识点"><span class="toc-text">结构体和方法补充知识点</span></a></li></ol></li></ol>
  </div>


  </div>
</div>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=5sr5du46f27&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33" async="async"></script>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>


  
    <div class="post-nav" style="margin-left:-168px;">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/08/27/k8sAPI的使用/" rel="next" title="python之kubernetes api 使用">
          python之kubernetes api 使用
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/08/29/Go语言之函数的闭包和匿名函数/" rel="prev" title="GO语言之函数的闭包和匿名函数">
            GO语言之函数的闭包和匿名函数
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


	
	<div style="width:109%; margin-left:-144px" id="lv-container" data-id="city" data-uid="MTAyMC80OTg5NS8yNjM4Ng==">
	<script type="text/javascript">
   	   (function(d, s) {
       		var j, e = d.getElementsByTagName(s)[0];

       		if (typeof LivereTower === 'function') { return; }

       		j = d.createElement(s);
       		j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
       		j.async = true;

       		e.parentNode.insertBefore(j, e);
   	   })(document, 'script');
	</script>
	<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
        </div>
	



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href target="_blank">GitHub</a> |
        <a class="bottom-item" href>友情链接</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/fooying/hexo-theme-xoxo-plus" target="_blank">Theme xoxo-plus</a> |
        <a class="bottom-item" href="/atom.xml">订阅</a>
    </div>
</footer>

  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



  

</body>
</html>
